package com.chookss;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baidu.mobstat.StatService;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.bun.miitmdid.core.MdidSdkHelper;
import com.bun.supplier.IIdentifierListener;
import com.bun.supplier.IdSupplier;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.NavigationBaseActivity;
import com.chookss.home.audit.PaySlipActivity;
import com.chookss.home.audit.WorkCardActivity;
import com.chookss.home.audit.clockIn.ClockInAskHolidayActivity;
import com.chookss.home.audit.clockIn.ClockInHomeActivity;
import com.chookss.home.audit.overtime.OvertimeActivity;
import com.chookss.home.audit.project.ProjectManagementActivity;
import com.chookss.home.audit.reimbursement.ReimbursementActivity;
import com.chookss.home.audit.resign.ResignHomeActivity;
import com.chookss.home.audit.seal.SealHomeActivity;
import com.chookss.home.audit.shop.ShopActivity;
import com.chookss.home.audit.upgrade.UpgradeHomeActivity;
import com.chookss.home.entity.DocunmentEntity;
import com.chookss.home.entity.NavigationEntity;
import com.chookss.home.gallery.PublishGalleryActivity;
import com.chookss.home.inspection.InspectionHomeActivity;
import com.chookss.home.interview.InterviewRecordsActivity;
import com.chookss.home.interview.InvitationRegisterActivity;
import com.chookss.home.knowledge.KnowledgeMoreFunctionActivity;
import com.chookss.home.other.ScanActivity;
import com.chookss.home.publish.PublishLogsActivity;
import com.chookss.home.publish.PublishNewsActivity;
import com.chookss.home.publish.PublishVedioActivity;
import com.chookss.home.running.RunningHomeActivity;
import com.chookss.home.search.MySearchActivity;
import com.chookss.home.tuwen.PublishTuwensActivity;
import com.chookss.home.update.InstallLocalApk;
import com.chookss.home.workbench.WorksActivity;
import com.chookss.login.LoginQrCodeActivity;
import com.chookss.mvp.presenter.HomeKnowledgePresenter;
import com.chookss.mvp.view.IBaseView;
import com.chookss.push.PushUtils;
import com.chookss.tiku.view.FlowLayout;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionSpUtils;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.video.VideoBaseActivity;
import com.chookss.video.entity.VideoEntity;
import com.chookss.view.ForScreenDialog;
import com.chookss.view.GlideEngine;
import com.chookss.view.HomeAdvertDialog;
import com.chookss.view.ImageFileCompressEngine;
import com.chookss.view.UpdateDialog;
import com.chookss.view.listener.HomeBottomDialogListener;
import com.chookss.view.listener.ShareDialogListener;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import scut.carson_ho.searchview.EditText_Clear;

/**
 * @author geyifeng
 * @date 2017/7/20
 */
public class HomeKnowledgeActivity extends BaseAct implements IBaseView {

    @BindView(R.id.llSm)
    LinearLayout llSm;
    @BindView(R.id.llSearch)
    LinearLayout llSearch;
    @BindView(R.id.rcvView)
    RecyclerView rcvView;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.tvSearch)
    TextView tvSearch;
    @BindView(R.id.etSearch)
    EditText_Clear etSearch;
    @BindView(R.id.iv1)
    ImageView iv1;
    @BindView(R.id.iv3)
    ImageView iv3;
    @BindView(R.id.llBottom)
    LinearLayout llBottom;
    @BindView(R.id.llAll)
    LinearLayout llAll;
    @BindView(R.id.flowLayout)
    FlowLayout flowLayout;
    @BindView(R.id.llHistory)
    LinearLayout llHistory;
    private List<String> lists = new ArrayList<>();
    private FlowAdapter flowAdapter;
    private String navigationCode1 = "13";//默认是13题库  03是资料库  14视频
    private String navigationCode3 = "14";//默认是13题库  03是资料库   14视频19也是视频
    private int GET_UNKNOWN_APP_SOURCES = 0x104;
    private String fileName = "", fileUrl = "";
    private HomeKnowledgeDialogAdapter adapter;
    private List<NavigationEntity> navigationEntityList = new ArrayList<>();
    private HomeBottomDialogListener listener = null;
    private boolean isDelete = false;//是否删除状态
    private HomeKnowledgePresenter homePagePresenter;
    private Context mContexts;
    private boolean isFirst = false;//当次启动是否是第一次进来  true是第一次，只有第一次才加载广告弹窗

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_knowledge);
        isFirst = getIntent().getBooleanExtra("isFirst", false);
        homePagePresenter = new HomeKnowledgePresenter(this, this);
        ButterKnife.bind(this);
        //特殊纪念日 主题变灰
        if(MyApp.THEME){
            Paint paint = new Paint();
            ColorMatrix cm = new ColorMatrix();
            cm.setSaturation(0);//灰度效果
            paint.setColorFilter(new ColorMatrixColorFilter(cm));
            getWindow().getDecorView().setLayerType(View.LAYER_TYPE_HARDWARE,paint);
        }
    }

    @Override
    public void initData() {
        initState();
        if (isDestroyed() || isFinishing() || this == null) {
            return;
        }
        //                01  公告管理 02  我的日志 03  资料库 04  学习计划
//                05  我的考试 06  一键面试 07  通讯录 08  个人能力
//                09 我的待办10 发布视频11 发布新闻12发布日志13题库14视频15溯源16发布图文17图文
        navigationCode1 = new ShareUtils().getString(this, StaticClass.BOTTOM_1_CODE, "13");
        navigationCode3 = new ShareUtils().getString(this, StaticClass.BOTTOM_3_CODE, "14");
        if ("01".equals(navigationCode1)) {
            iv1.setBackgroundResource(R.mipmap.gonggao);
        } else if ("02".equals(navigationCode1)) {
            iv1.setBackgroundResource(R.mipmap.rizhi);
        } else if ("03".equals(navigationCode1)) {
            iv1.setBackgroundResource(R.mipmap.docunment);
        } else if ("04".equals(navigationCode1)) {
            iv1.setBackgroundResource(R.mipmap.xuexijihua);
        } else if ("05".equals(navigationCode1)) {
            iv1.setBackgroundResource(R.mipmap.kaoshi);
        } else if ("06".equals(navigationCode1)) {
            iv1.setBackgroundResource(R.mipmap.yijianmianshi);
        } else if ("07".equals(navigationCode1)) {
            iv1.setBackgroundResource(R.mipmap.tongxunlu);
        } else if ("08".equals(navigationCode1)) {
            iv1.setBackgroundResource(R.mipmap.gerennengli);
        } else if ("15".equals(navigationCode1)) {
            iv1.setBackgroundResource(R.mipmap.suyuan);
        } else if ("17".equals(navigationCode1)) {
            iv1.setBackgroundResource(R.mipmap.tuwen);
        } else if ("14".equals(navigationCode1) || "19".equals(navigationCode1)) {
            iv1.setBackgroundResource(R.mipmap.shipin);
        } else if ("24".equals(navigationCode1)) {
            iv1.setBackgroundResource(R.drawable.zhishiku);
        } else if ("26".equals(navigationCode1)) {
            iv1.setBackgroundResource(R.mipmap.gallery);
        } else {
            iv1.setBackgroundResource(R.mipmap.tiku);
        }
        if ("01".equals(navigationCode3)) {
            iv3.setBackgroundResource(R.mipmap.gonggao);
        } else if ("02".equals(navigationCode3)) {
            iv3.setBackgroundResource(R.mipmap.rizhi);
        } else if ("03".equals(navigationCode3)) {
            iv3.setBackgroundResource(R.mipmap.docunment);
        } else if ("04".equals(navigationCode3)) {
            iv3.setBackgroundResource(R.mipmap.xuexijihua);
        } else if ("05".equals(navigationCode3)) {
            iv3.setBackgroundResource(R.mipmap.kaoshi);
        } else if ("06".equals(navigationCode3)) {
            iv3.setBackgroundResource(R.mipmap.yijianmianshi);
        } else if ("07".equals(navigationCode3)) {
            iv3.setBackgroundResource(R.mipmap.tongxunlu);
        } else if ("08".equals(navigationCode3)) {
            iv3.setBackgroundResource(R.mipmap.gerennengli);
        } else if ("15".equals(navigationCode3)) {
            iv3.setBackgroundResource(R.mipmap.suyuan);
        } else if ("17".equals(navigationCode3)) {
            iv3.setBackgroundResource(R.mipmap.tuwen);
        } else if ("13".equals(navigationCode3)) {
            iv3.setBackgroundResource(R.mipmap.tiku);
        } else if ("24".equals(navigationCode3)) {
            iv3.setBackgroundResource(R.drawable.zhishiku);
        } else if ("26".equals(navigationCode3)) {
            iv3.setBackgroundResource(R.mipmap.gallery);
        } else {
            iv3.setBackgroundResource(R.mipmap.shipin);
        }
        etSearch.setSearchIconVisible();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 5);
        rcvView.setLayoutManager(gridLayoutManager);
        adapter = new HomeKnowledgeDialogAdapter(R.layout.item_home_knowledge_dialog, this, navigationEntityList);
        rcvView.setAdapter(adapter);
        registerBoradcastReceiver();

        Observable.timer(800, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) {
                        try {
                            MyApp.initX5();
                            StatService.setAuthorizedState(HomeKnowledgeActivity.this, true);
                            StatService.start(HomeKnowledgeActivity.this);
                            MdidSdkHelper.InitSdk(HomeKnowledgeActivity.this, true, new IIdentifierListener() {
                                @Override
                                public void OnSupport(boolean b, IdSupplier idSupplier) {
                                    if (idSupplier != null && idSupplier.isSupported())
                                        StatService.setOaid(HomeKnowledgeActivity.this, idSupplier.getOAID());
                                }
                            });
//                            String channel = WalleChannelReader.getChannel(HomeKnowledgeActivity.this,"official");
                            //获取权限
                            if ("13503825592".equals(new ShareUtils().getString(HomeKnowledgeActivity.this, StaticClass.USERNAME, ""))||"13300000000".equals(new ShareUtils().getString(HomeKnowledgeActivity.this, StaticClass.USERNAME, ""))||"小竹体验中心".equals(new ShareUtils().getString(HomeKnowledgeActivity.this, StaticClass.COMPANYNAME, ""))) {
                            }else{
                                requestSTORAGE();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    tvSearch.setVisibility(View.VISIBLE);
                    llSm.setVisibility(View.GONE);
                } else {
                    tvSearch.setVisibility(View.GONE);
                    llSm.setVisibility(View.VISIBLE);
                }
            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {   // 按下完成按钮，这里和上面imeOptions对应
                    if (!Utils.isNull(v.getText().toString())) {
                        add(etSearch.getText().toString());
                        if (etSearch != null) {
                            etSearch.setCursorVisible(false);
                            Utils.hideInputKeyboard(HomeKnowledgeActivity.this, etSearch);
                            //隐藏光标
                            rcvView.setVisibility(View.VISIBLE);
                            llHistory.setVisibility(View.GONE);
                        }
                        Intent intent = new Intent(HomeKnowledgeActivity.this, MySearchActivity.class);
                        intent.putExtra("key", etSearch.getText().toString());
                        startActivity(intent);
                        return false;   //返回true，保留软键盘。false，隐藏软键盘
                    } else {
                        MyToast.show("请输入关键词");
                    }
                }
                return true;   //返回true，保留软键盘。false，隐藏软键盘
            }
        });
        etSearch.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (MotionEvent.ACTION_DOWN == event.getAction()) {
                    etSearch.setCursorVisible(true);
                    //显示光标
                    if (lists.size() > 0) {
                        llHistory.setVisibility(View.VISIBLE);
                    }
                    rcvView.setVisibility(View.GONE);
                }
                return false;
            }
        });
        String text = new ShareUtils().getString(this,Utils.getCacheName(this,StaticClass.ALL_HISTORY), "");
        if (!Utils.isNull(text)) {
            List<String> stringList = JSONArray.parseArray(text, String.class);
            if (stringList != null) {
                lists.addAll(stringList);
            }
        }
        if (lists.size() > 0) {
            flowAdapter = new FlowAdapter(this, lists);
            flowLayout.setAdapter(flowAdapter);
        }
        //判断是否有推送缓存
        if (!Utils.isNull(new ShareUtils().getString(this, StaticClass.PUSH_DATA, ""))) {
            PushUtils.getPushData(this);
        }
        getNavigations();
        //只要启动调用
        homePagePresenter.checkLogin();
        homePagePresenter.getNavigations();
        homePagePresenter.getCostConfig();
        homePagePresenter.getMineInfo();
        //水印只有启动和切换账号才获取
        homePagePresenter.getWatermarkList();
        homePagePresenter.getOSSkey();
    }
    public void getNavigations() {
        //获取导航
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<NavigationEntity>>>() {
        }.getType(), null, Urls.getMyNavigation, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<NavigationEntity>>() {
            @Override
            public void onSuccess(List<NavigationEntity> data) {
                if (data.size() > 0) {
                    navigationEntityList.clear();
                    navigationEntityList.addAll(data);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(errorMsg);
            }
        });
    }

    private void requestSTORAGE() {
        XXPermissions.with(this)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        getVersion();
                       }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        getVersion();
                    }
                });
    }

    private void getVersion() {
        Map<String, String> map = new HashMap<>();
        map.put("system", "0");
        if (getPackageName().equals("com.zhaofengnum")) {
            map.put("downloadAddress", "zhaofeng");
        }
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.getVersion, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        int versionCode = Utils.changeNumber(jsonObject1.getString("versionCode"));
                        if (versionCode > Utils.getVersionCode(HomeKnowledgeActivity.this)) {
                            fileUrl = jsonObject1.getString("downloadAddress");
                            fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
                            new UpdateDialog(HomeKnowledgeActivity.this, jsonObject1.getString("versionName"), jsonObject1.getString("versionDesc"), jsonObject1.getString("updateFlag"), fileUrl,
                                    new ShareDialogListener() {
                                        @Override
                                        public void onClick() {
                                            // 如果是8.0系统
                                            if (Build.VERSION.SDK_INT >= 30) {
                                                InstallLocalApk.install(HomeKnowledgeActivity.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                                            } else if (Build.VERSION.SDK_INT >= 26) {
                                                boolean b = getPackageManager().canRequestPackageInstalls();
                                                // 如果已经打开了安装未知来源的开关
                                                if (b) {
                                                    InstallLocalApk.install(HomeKnowledgeActivity.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                                                } else {
                                                    // 请求打开安装未知应用来源的界面,非运行时权限
                                                    Uri packageURI = Uri.parse("package:" + getPackageName());
                                                    Intent intents = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                                                    startActivityForResult(intents, GET_UNKNOWN_APP_SOURCES);
                                                }
                                            } else {
                                                InstallLocalApk.install(HomeKnowledgeActivity.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                                            }
                                        }
                                    }).show();
                        } else {
                            checkBdWx();
                        }
                    } else {
                        checkBdWx();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    checkBdWx();
                }
            }

            @Override
            public void onError(String errorMsg) {
                checkBdWx();
            }
        });
    }

    private void checkBdWx() {
        if (!isFirst) {
            return;
        }
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.checkBdWx, SignUtils2.makeSignStr(null), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {
                JSONObject reObject = new JSONObject(data);
                if ("200".equals(reObject.getString("code"))) {
                    JSONObject jsonObject = reObject.getJSONObject("data");
                    if ("1".equals(jsonObject.getString("tanchuang"))) {
                        new ShareUtils().putBoolean(HomeKnowledgeActivity.this, StaticClass.BIND_WX, false);
                        try {
                            if (!Utils.isNull(jsonObject.getString("imagePath"))) {
                                Glide.with(HomeKnowledgeActivity.this).asBitmap()
                                        .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).load(jsonObject.getString("imagePath"))
                                        .into(new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(@androidx.annotation.NonNull Bitmap resource, @androidx.annotation.Nullable Transition<? super Bitmap> transition) {
                                                try {
                                                    if (resource != null) {
                                                        new HomeAdvertDialog(HomeKnowledgeActivity.this, resource, jsonObject.getString("longUrl")).show();
                                                    }
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        });
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        new ShareUtils().putBoolean(HomeKnowledgeActivity.this, StaticClass.BIND_WX, true);
                        new ShareUtils().putLong(HomeKnowledgeActivity.this, StaticClass.EMPLOYEECODE + "-" + StaticClass.BIND_WX_TIME, 0);

                    }
                } else {
                    MyToast.show(reObject.getString("msg"));
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("downApk"); // 获取数据
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                fileName = intent.getStringExtra("fileName");
                int percent = intent.getIntExtra("percent", 0);
                if (percent == 100) {
                    // 如果是8.0系统
                    if (Build.VERSION.SDK_INT >= 30) {
                        InstallLocalApk.install(HomeKnowledgeActivity.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                    } else if (Build.VERSION.SDK_INT >= 26) {
                        boolean b = getPackageManager().canRequestPackageInstalls();
                        // 如果已经打开了安装未知来源的开关
                        if (b) {
                            InstallLocalApk.install(HomeKnowledgeActivity.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                        } else {
                            // 请求打开安装未知应用来源的界面,非运行时权限
                            Uri packageURI = Uri.parse("package:" + getPackageName());
                            Intent intents = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                            startActivityForResult(intents, GET_UNKNOWN_APP_SOURCES);
                        }
                    } else {
                        InstallLocalApk.install(HomeKnowledgeActivity.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                    }
                }
            }
        }
    };

    private void requestSTORAGECamer(int position) {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            if (position == 0) {
                                //视频
                                PictureSelector.create(HomeKnowledgeActivity.this)
                                        .openGallery(SelectMimeType.ofVideo())
                                        .isDisplayCamera(true)//是否显示相机入口
                                        .setMaxVideoSelectNum(1)
                                        .setMaxSelectNum(1)
                                        .setSelectionMode(SelectModeConfig.SINGLE)//单选
                                        .isPreviewVideo(true)//是否支持预览视频
                                        .setSelectMinFileSize(50)//过滤最小文件50k
                                        .setFilterVideoMaxSecond(600)//过滤最大视频选择600s
                                        .setRecordVideoMaxSecond(30)//过滤录制最大30s
                                        .isFilterSizeDuration(true)//是否过滤图片或音视频大小时长为0的资源
                                        .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                        .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                        .forResult(PictureConfig.REQUEST_CAMERA);
                            } else {
                                //图片
                                PictureSelector.create(HomeKnowledgeActivity.this)
                                        .openGallery(SelectMimeType.ofImage())
                                        .isDisplayCamera(true)//是否显示相机入口
                                        .setMaxSelectNum(9)
                                        .setSelectionMode(SelectModeConfig.MULTIPLE)//多选
                                        .isPreviewImage(true)//是否支持预览图片
                                        .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                                        .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                        .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                            }
                        } else {
                            PermissionUtils.errorPermission(HomeKnowledgeActivity.this, granted, all);
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(HomeKnowledgeActivity.this, denied, quick);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PictureConfig.REQUEST_CAMERA) {
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                Intent intent = new Intent(HomeKnowledgeActivity.this, PublishVedioActivity.class);
                String url = "";
                if (selectList.get(0).getPath().contains("content://")) {
                    Uri uri = Uri.parse(selectList.get(0).getPath());
                    url = PathUtil.getPath(this, uri);
                } else {
                    url = selectList.get(0).getPath();
                }
                intent.putExtra("fileUrl", url);
                KLog.i("原图::" + selectList.get(0).getPath());
                KLog.i("Android Q 特有Path::" + Uri.parse(selectList.get(0).getPath()).toString());
                startActivity(intent);
            } else if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 如果是直接从相册获取
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                ArrayList<String> imgList = new ArrayList<>();
                for (int i = 0; i < selectList.size(); i++) {
                    KLog.i("压缩::" + selectList.get(0).getCompressPath());
                    KLog.i("原图::" + selectList.get(0).getPath());
                    String url = "";
                    if (!Utils.isNull(selectList.get(i).getCompressPath())) {
                        if (selectList.get(i).getCompressPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getCompressPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getCompressPath();
                        }
                    } else {
                        if (selectList.get(i).getPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getPath();
                        }
                    }
                    imgList.add(url);
                    KLog.i("Android Q 特有Path::" + url);
                }
                if (imgList.size() > 0) {
                    Intent intent = new Intent(HomeKnowledgeActivity.this, PublishGalleryActivity.class);
                    intent.putStringArrayListExtra("imgUrls", imgList);
                    startActivity(intent);
                }
            } else if (requestCode == GET_UNKNOWN_APP_SOURCES) {
                InstallLocalApk.install(HomeKnowledgeActivity.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
            }
        }
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
//                MyToast.show("扫码取消");
            } else {
                String content = result.getContents();
                KLog.i("扫描成功: " + content);
                Intent intent = null;
                if (content.contains("scan?code=")) {
                    String[] codes = content.split("code=");
                    if (codes.length > 1) {
                        getData(codes[1]);
                    } else {
                        MyToast.show("扫描数据异常，请稍后重试");
                    }
                } else if (content.contains("resourceType") && content.contains("resourceId")) {
//                    （1资料，2长视频，3短视频）
//                    扫描成功:resourceType=3&resourceId=b81127c1b7a344729b1b528588b6f479&employeeCode=EMP202109060001
                    String datas[] = content.split("&");
                    if (datas.length > 2) {
                        try {
                            String resourceType = datas[0].split("=")[1];
                            String resourceId = datas[1].split("=")[1];
                            String employeeCode = datas[2].split("=")[1];
                            String localCode = new ShareUtils().getString(HomeKnowledgeActivity.this, StaticClass.EMPLOYEECODE, "");
                            if (!employeeCode.equals(localCode)) {
                                MyToast.show("请扫描自己后台中的二维码");
                                return;
                            }
                            if (datas.length > 4) {
                                String currentTime = datas[3].split("=")[1];
                                int validLength = Integer.parseInt(datas[4].split("=")[1]);
                                long time = System.currentTimeMillis() - Long.parseLong(currentTime);
                                if (time / 1000 > validLength) {
                                    MyToast.show("二维码已失效，请刷新后重试");
                                } else {
                                    if ("1".equals(resourceType)) {
                                        getDocunmentData(resourceId);
                                    } else if ("2".equals(resourceType) || "3".equals(resourceType)) {
                                        getViedeo(resourceType, resourceId);
                                    }
                                }
                            } else {
                                if ("1".equals(resourceType)) {
                                    getDocunmentData(resourceId);
                                } else if ("2".equals(resourceType) || "3".equals(resourceType)) {
                                    getViedeo(resourceType, resourceId);
                                }
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            MyToast.show("二维码异常，请稍后重试");
                        }
                    }

                } else if (content.startsWith("http")) {
                    intent = new Intent(this, WebCommonActivity.class);
                    intent.putExtra("url", content);
                    startActivity(intent);
                } else {
                    getData(content);
                }

            }
        }
    }

    private void getViedeo(String type, String id) {
        if (!PermissionSpUtils.getBoolean(this,"14",false)) {
            MyToast.show("管理员已关闭视频功能");
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("videoId", id);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<VideoEntity>>() {
        }.getType(), null, Urls.selectAPPVideoById, SignUtils2.makeSignStr(map), false, new ObserverCallback<VideoEntity>() {
            @Override
            public void onSuccess(VideoEntity data) {
                if (Utils.isNull(data.videoId)) {
                    MyToast.show("视频id为空");
                    return;
                }
                new ForScreenDialog(HomeKnowledgeActivity.this, type, data).show();
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getDocunmentData(String dataCode) {
        if (!PermissionSpUtils.getBoolean(this,"03",false)) {
            MyToast.show("管理员已关闭资料库功能");
            return;
        }
        Map<String, String> allmap = new HashMap<>();
        allmap.put("dataCode", dataCode);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<DocunmentEntity>>() {
        }.getType(), null, Urls.getDetail, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<DocunmentEntity>() {
            @Override
            public void onSuccess(DocunmentEntity data) {
                if (data != null) {
                    new ForScreenDialog(HomeKnowledgeActivity.this, data).show();
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getData(String loginUid) {
        showLoading();
        Map<String, String> map = new HashMap<>();
        map.put("loginUid", loginUid);
        MyHttpRequest.getRequest(Urls.checkQRStatus, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        Intent intent = new Intent(HomeKnowledgeActivity.this, LoginQrCodeActivity.class);
                        intent.putExtra("loginUid", loginUid);
                        intent.putExtra("status", jsonObject1.getString("status"));
                        startActivity(intent);
                    }else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private long lastBackPressedTime = 0L;

    @Override
    protected void onRestart() {
        super.onRestart();
        isDelete = false;
        if (navigationEntityList.size() > 0) {
            navigationEntityList.remove(navigationEntityList.size() - 1);
            adapter.notifyDataSetChanged();
        }
        llBottom.setVisibility(View.VISIBLE);
        tvSure.setVisibility(View.GONE);
        getNavigations();
    }

    @Override
    public Context getContext() {
        return this;
    }

    class HomeKnowledgeDialogAdapter extends BaseQuickAdapter<NavigationEntity, BaseViewHolderEx> {
        private Context mContext;
        private ArrayList<NavigationEntity> data;

        public HomeKnowledgeDialogAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<NavigationEntity> data) {
            super(layoutResId, data);
            this.mContext = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, NavigationEntity entity) {
            ImageView ivNavigation = helper.getView(R.id.ivNavigation);
            TextView tvNavigation = helper.getView(R.id.tvNavigation);
            ImageView ivDelete = helper.getView(R.id.ivDelete);
            ImageView ivAdd = helper.getView(R.id.ivAdd);
            tvNavigation.setText(entity.getNavigationName());
            if (isDelete) {
                if (entity.getNavigationCode().equals("0")) {
                    ivDelete.setVisibility(View.GONE);
                } else {
                    ivDelete.setVisibility(View.VISIBLE);
                }
            } else {
                ivDelete.setVisibility(View.GONE);
            }
            if (entity.getNavigationCode().equals("0")) {
                ivAdd.setVisibility(View.VISIBLE);
                ivNavigation.setVisibility(View.GONE);
            } else {
                GlideUtils.load(mContext, entity.getNavigationImg(), ivNavigation, R.drawable.default_news);
                ivAdd.setVisibility(View.GONE);
                ivNavigation.setVisibility(View.VISIBLE);
            }
            tvNavigation.setText(entity.getNavigationName());
            ivDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    saveUseRecord(entity.getNavigationCode(), helper.getItemPosition());
                }
            });
            ivAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, KnowledgeMoreFunctionActivity.class);
                    intent.putExtra("type", 1);
                    ArrayList<NavigationEntity> selectList = new ArrayList<>();
                    selectList.addAll(navigationEntityList.subList(0, navigationEntityList.size() - 1));
                    intent.putExtra("selectData", selectList);
                    mContext.startActivity(intent);
                }
            });
            helper.getItemView().setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    isDelete = true;
                    if (!navigationEntityList.get(navigationEntityList.size() - 1).getNavigationCode().equals("0")) {
                        NavigationEntity navigationEntity = new NavigationEntity();
                        navigationEntity.setNavigationName("添加");
                        navigationEntity.setNavigationCode("0");
                        navigationEntity.setLocalUrl(R.drawable.bg_xiezhoubao);
                        navigationEntityList.add(navigationEntity);
                    }
                    adapter.notifyDataSetChanged();
                    llBottom.setVisibility(View.GONE);
                    tvSure.setVisibility(View.VISIBLE);
                    return true;
                }
            });
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isDelete) {
                        //删除情况下不能点击进入
                        return;
                    }
                    //12写日志
                    // 01公告 02 日志 03资料 04学习计划05考试 06 面试 07 通讯录 08  个人能力09 我的待办10 发布视频11 发布新闻12发布日志13题库14视频15溯源
                    //    16图文发布17图文18邀请注册19 图库  20 面试评价 21写日报  22写周报 23写月报24知识库25发布图库26图库27考勤28请假29电子工牌
                    Intent intent = null;
                    KLog.i(entity.getNavigationCode() + "====");
                    if ("01".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, NavigationBaseActivity.class);
                        intent.putExtra("type", 1);
                        mContext.startActivity(intent);
                    } else if ("02".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, NavigationBaseActivity.class);
                        intent.putExtra("type", 2);
                        mContext.startActivity(intent);
                    } else if ("03".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, NavigationBaseActivity.class);
                        intent.putExtra("type", 3);
                        mContext.startActivity(intent);
                    } else if ("04".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, NavigationBaseActivity.class);
                        intent.putExtra("type", 4);
                        mContext.startActivity(intent);
                    } else if ("05".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, NavigationBaseActivity.class);
                        intent.putExtra("type", 5);
                        mContext.startActivity(intent);
                    } else if ("06".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, NavigationBaseActivity.class);
                        intent.putExtra("type", 6);
                        mContext.startActivity(intent);
                    } else if ("07".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, NavigationBaseActivity.class);
                        intent.putExtra("type", 7);
                        mContext.startActivity(intent);
                    } else if ("08".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, WebCommonActivity.class);
                        String url = NavigationTools.getAllUrl2(mContext, Urls.getCapacityAnalysisCapacity) + "&employeeCode=" + new ShareUtils().getString(mContext, StaticClass.EMPLOYEECODE, "");
                        if (url != null) {
                            intent.putExtra("url", url);
                            intent.putExtra("isPersonalAbility", true);
                            intent.putExtra("title", "个人能力分析");
                            mContext.startActivity(intent);
                        }
                    } else if ("09".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, WorksActivity.class);
                        mContext.startActivity(intent);
                    } else if ("10".equals(entity.getNavigationCode())) {
                        if (Utils.isNull(MyApp.accessKeyId)) {
                            MyToast.show("暂无权限上传视频");
                        } else {
                            requestSTORAGECamer(0);
                        }
                    } else if ("11".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, PublishNewsActivity.class);
                        mContext.startActivity(intent);
                    } else if ("12".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, PublishLogsActivity.class);
                        intent.putExtra("type", 3);
                        mContext.startActivity(intent);
                    } else if ("21".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, PublishLogsActivity.class);
                        intent.putExtra("type", 0);
                        mContext.startActivity(intent);
                    } else if ("22".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, PublishLogsActivity.class);
                        intent.putExtra("type", 1);
                        mContext.startActivity(intent);
                    } else if ("23".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, PublishLogsActivity.class);
                        intent.putExtra("type", 2);
                        mContext.startActivity(intent);
                    } else if ("13".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, NavigationBaseActivity.class);
                        intent.putExtra("type", 0);
                        mContext.startActivity(intent);
                    } else if ("14".equals(entity.getNavigationCode())) {
                        //小视频
                        intent = new Intent(mContext, VideoBaseActivity.class);
                        mContext.startActivity(intent);
                    } else if ("15".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, NavigationBaseActivity.class);
                        intent.putExtra("type", 15);
                        mContext.startActivity(intent);
                    } else if ("16".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, PublishTuwensActivity.class);
                        mContext.startActivity(intent);
                    } else if ("17".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, NavigationBaseActivity.class);
                        intent.putExtra("type", 17);
                        mContext.startActivity(intent);
                    } else if ("18".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, InvitationRegisterActivity.class);
                        mContext.startActivity(intent);
                    } else if ("19".equals(entity.getNavigationCode())) {
                        //小视频
                        intent = new Intent(mContext, VideoBaseActivity.class);
                        intent.putExtra("index", 1);
                        mContext.startActivity(intent);
                    } else if ("20".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, InterviewRecordsActivity.class);
                        intent.putExtra("type", 2);
                        mContext.startActivity(intent);
                    } else if ("24".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, NavigationBaseActivity.class);
                        intent.putExtra("type", 24);
                        mContext.startActivity(intent);
                    } else if ("25".equals(entity.getNavigationCode())) {
                        requestSTORAGECamer(1);
                    } else if ("26".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, NavigationBaseActivity.class);
                        intent.putExtra("type", 26);
                        mContext.startActivity(intent);
                    }else if ("27".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, ClockInHomeActivity.class);
                        mContext.startActivity(intent);
                    }else if ("28".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, ClockInAskHolidayActivity.class);
                        mContext.startActivity(intent);
                    }else if ("29".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, WorkCardActivity.class);
                        mContext.startActivity(intent);
                    }else if ("30".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, ReimbursementActivity.class);
                        mContext.startActivity(intent);
                    }else if ("31".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, ShopActivity.class);
                        mContext.startActivity(intent);
                    }else if ("32".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, ReimbursementActivity.class);
                        intent.putExtra("type",9);
                        mContext.startActivity(intent);
                    }else if ("33".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, ReimbursementActivity.class);
                        intent.putExtra("type",10);
                        mContext.startActivity(intent);
                    }else if ("34".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, RunningHomeActivity.class);
                        mContext.startActivity(intent);
                    }else if ("35".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, SealHomeActivity.class);
                        mContext.startActivity(intent);
                    }else if ("36".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, InspectionHomeActivity.class);
                        mContext.startActivity(intent);
                    }else if ("37".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, PaySlipActivity.class);
                        mContext.startActivity(intent);
                    }else if ("38".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, ResignHomeActivity.class);
                        mContext.startActivity(intent);
                    }else if ("39".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, UpgradeHomeActivity.class);
                        mContext.startActivity(intent);
                    }else if ("40".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, ProjectManagementActivity.class);
                        mContext.startActivity(intent);
                    }else if("41".equals(entity.getNavigationCode())) {
                        intent = new Intent(mContext, OvertimeActivity.class);
                        mContext.startActivity(intent);
                    }
                }
            });
        }
    }

    public void saveUseRecord(String navigationCode, int position) {
        //状态（0 取消/1 添加）
        Map<String, String> map = new HashMap<>();
        map.put("statusCd", "0");
        map.put("navigationCode", navigationCode);
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<String>>() {
        }.getType(), null, Urls.setNavigation, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                navigationEntityList.remove(position);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    class FlowAdapter extends FlowLayout.Adapter<FlowAdapter.FlowViewHolder> {

        private static final String TAG = "FlowAdapter";

        private Context mContext;
        private List<String> mContentList;

        public FlowAdapter(Context mContext, List<String> mContentList) {
            this.mContext = mContext;
            this.mContentList = mContentList;
        }

        @Override
        public FlowAdapter.FlowViewHolder onCreateViewHolder(ViewGroup parent) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_search_list, parent, false);
//            // 给 View 设置 margin
            ViewGroup.MarginLayoutParams mlp = new ViewGroup.MarginLayoutParams(view.getLayoutParams());
            int margin = Utils.dip2px(mContext, 6);
            mlp.setMargins(margin, margin, margin, margin);
            view.setLayoutParams(mlp);

            return new FlowAdapter.FlowViewHolder(view);
        }

        @Override
        public void onBindViewHolder(FlowAdapter.FlowViewHolder holder, int position) {
            holder.tvTitle.setText(mContentList.get(position));
            holder.ivDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    remove(position);
                }
            });
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    etSearch.setText(mContentList.get(position));
                    Intent intent = new Intent(HomeKnowledgeActivity.this, MySearchActivity.class);
                    intent.putExtra("key", etSearch.getText().toString());
                    startActivity(intent);
                    if (etSearch != null) {
                        etSearch.setCursorVisible(false);
                        Utils.hideInputKeyboard(HomeKnowledgeActivity.this, etSearch);
                        //隐藏光标
                        rcvView.setVisibility(View.VISIBLE);
                        llHistory.setVisibility(View.GONE);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return mContentList.size();
        }

        class FlowViewHolder extends FlowLayout.ViewHolder {
            TextView tvTitle;
            ImageView ivDelete;

            public FlowViewHolder(View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tvTitle);
                ivDelete = itemView.findViewById(R.id.ivDelete);
            }
        }
    }

    private void add(String data) {
        // 设置 Adapter
        if (flowLayout == null) {
            return;
        }
        llHistory.setVisibility(View.VISIBLE);
        if (!lists.contains(data)) {
            lists.add(data);
            saveSearchHistory();
            // 设置 Adapter
            flowAdapter = new FlowAdapter(this, lists);
            flowLayout.setAdapter(flowAdapter);
        }
    }

    private void remove(int position) {
        // 设置 Adapter
        if (flowLayout == null) {
            return;
        }
        lists.remove(position);
        saveSearchHistory();
        // 设置 Adapter
        if (lists.size() > 0) {
            flowLayout.setVisibility(View.VISIBLE);
            flowAdapter = new FlowAdapter(this, lists);
            flowLayout.setAdapter(flowAdapter);
        } else {
            flowLayout.setVisibility(View.GONE);
        }
    }


    private void saveSearchHistory() {
        if (lists.size() > 6) {
            lists.remove(0);
        }
        String text = JSON.toJSONString(lists);
        new ShareUtils().putString(this, Utils.getCacheName(this,StaticClass.ALL_HISTORY), text);
    }

    @OnClick({R.id.llvDelele, R.id.llSm, R.id.tvSearch, R.id.tvSure, R.id.rlHome, R.id.rl1, R.id.rl3, R.id.llAll})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llSm:
                new IntentIntegrator(this)
                        .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)// 扫码的类型,可选：一维码，二维码，一/二维码
                        .setPrompt("请对准二维码")// 设置提示语
                        .setCameraId(0)// 选择摄像头,可使用前置或者后置
                        .setBeepEnabled(true)// 是否开启声音,扫完码之后会"哔"的一声
                        .setBarcodeImageEnabled(false)// 扫完码之后生成二维码的图片
                        .setOrientationLocked(false)//扫描方向固定
                        .setCaptureActivity(ScanActivity.class) // 设置自定义的activity是CustomActivity
                        .initiateScan();// 初始化扫码
                break;
            case R.id.llvDelele:
                if (flowLayout == null) {
                    return;
                }
                new ShareUtils().putString(this,Utils.getCacheName(this,StaticClass.ALL_HISTORY), "");
                lists.clear();
                llHistory.setVisibility(View.GONE);
                break;
            case R.id.tvSearch:
                add(etSearch.getText().toString());
                Intent intent = new Intent(this, MySearchActivity.class);
                intent.putExtra("key", etSearch.getText().toString());
                startActivity(intent);
                break;
            case R.id.tvSure:
                isDelete = false;
                if (navigationEntityList.size() > 0) {
                    navigationEntityList.remove(navigationEntityList.size() - 1);
                    adapter.notifyDataSetChanged();
                }
                llBottom.setVisibility(View.VISIBLE);
                tvSure.setVisibility(View.GONE);
                break;
            case R.id.rlHome:
                finish();
                break;
            case R.id.rl1:
                Intent intent1 = new Intent(this, HomeActivityss.class);
                intent1.putExtra("num", 1);
                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent1);
                finish();
                break;
            case R.id.rl3:
                Intent intent3 = new Intent(this, HomeActivityss.class);
                intent3.putExtra("num", 3);
                intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent3);
                finish();
                break;
            case R.id.llAll:
                if (etSearch != null) {
                    etSearch.setCursorVisible(false);
                    Utils.hideInputKeyboard(this, etSearch);
                }
                //隐藏光标
                rcvView.setVisibility(View.VISIBLE);
                llHistory.setVisibility(View.GONE);
                if (!isDelete) {
                    if (navigationEntityList.size() == 0) {
                        NavigationEntity navigationEntity = new NavigationEntity();
                        navigationEntity.setNavigationName("添加");
                        navigationEntity.setNavigationCode("0");
                        navigationEntity.setLocalUrl(R.drawable.bg_xiezhoubao);
                        navigationEntityList.add(navigationEntity);
                        adapter.notifyDataSetChanged();
                    } else {
                        if (navigationEntityList.get(navigationEntityList.size() - 1).getNavigationCode().equals("0")) {
                            navigationEntityList.remove(navigationEntityList.size() - 1);
                            adapter.notifyDataSetChanged();
                        } else {
                            if (navigationEntityList.size() < 10) {
                                NavigationEntity navigationEntity = new NavigationEntity();
                                navigationEntity.setNavigationName("添加");
                                navigationEntity.setNavigationCode("0");
                                navigationEntity.setLocalUrl(R.drawable.bg_xiezhoubao);
                                navigationEntityList.add(navigationEntity);
                                adapter.notifyItemChanged(navigationEntityList.size() - 1);
                            }
                        }

                    }
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();

        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("HomeOver")) {
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        new ShareUtils().putString(this, StaticClass.PUSH_DATA, "");
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
        if (etSearch != null) {
            Utils.hideInputKeyboard(this, etSearch);
        }
    }
}
